# HarmonyOS 完整构建脚本 (PowerShell版本)
Write-Host "🚀 开始完整的 HarmonyOS 构建流程..." -ForegroundColor Green

# 设置错误处理
$ErrorActionPreference = "Stop"

try {
    Write-Host ""
    Write-Host "📦 步骤 1: 安装依赖" -ForegroundColor Yellow
    npm install
    if ($LASTEXITCODE -ne 0) {
        throw "依赖安装失败"
    }
    Write-Host "✅ 依赖安装成功" -ForegroundColor Green

    Write-Host ""
    Write-Host "🔨 步骤 2: 构建 Ionic 应用" -ForegroundColor Yellow
    npm run build
    if ($LASTEXITCODE -ne 0) {
        throw "Ionic 构建失败"
    }
    Write-Host "✅ Ionic 构建成功" -ForegroundColor Green

    Write-Host ""
    Write-Host "📁 步骤 3: 复制文件到 HarmonyOS 项目" -ForegroundColor Yellow
    npm run build:harmonyos
    if ($LASTEXITCODE -ne 0) {
        throw "HarmonyOS 构建脚本失败"
    }
    Write-Host "✅ 文件复制成功" -ForegroundColor Green

    Write-Host ""
    Write-Host "🧹 步骤 4: 清理 HarmonyOS 项目" -ForegroundColor Yellow
    Set-Location ohos
    
    try {
        hvigor clean
        if ($LASTEXITCODE -ne 0) {
            Write-Host "⚠ HarmonyOS 清理失败，继续构建..." -ForegroundColor Yellow
        } else {
            Write-Host "✅ HarmonyOS 清理成功" -ForegroundColor Green
        }
    } catch {
        Write-Host "⚠ HarmonyOS 清理失败，继续构建..." -ForegroundColor Yellow
    }

    Write-Host ""
    Write-Host "🔨 步骤 5: 构建 HarmonyOS 应用" -ForegroundColor Yellow
    hvigor assembleHap
    if ($LASTEXITCODE -ne 0) {
        throw "HarmonyOS 应用构建失败"
    }
    Write-Host "✅ HarmonyOS 应用构建成功" -ForegroundColor Green

    Set-Location ..
    
    Write-Host ""
    Write-Host "🎉 构建完成！" -ForegroundColor Green
    Write-Host "📱 HAP 文件位置: ohos\entry\build\default\outputs\default\entry-default-signed.hap" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "📝 下一步操作：" -ForegroundColor Yellow
    Write-Host "1. 在 DevEco Studio 中打开 ohos 目录"
    Write-Host "2. 连接 HarmonyOS 设备或启动模拟器"
    Write-Host "3. 点击 Run 按钮运行应用"
    Write-Host ""

} catch {
    Write-Host ""
    Write-Host "❌ 构建失败: $($_.Exception.Message)" -ForegroundColor Red
    Set-Location $PSScriptRoot
    Read-Host "按任意键退出"
    exit 1
}

Read-Host "按任意键退出"